package com.example.Lezedata.ui.activity.home;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;

import androidx.annotation.RequiresApi;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.example.Lezedata.R;
import com.example.Lezedata.dataManager.LoginManager;
import com.example.Lezedata.dataModel.BidDetailManager;
import com.example.Lezedata.dataModel.GoodsProjectModel;
import com.example.Lezedata.net.GBError;
import com.example.Lezedata.net.GBNetRequest;
import com.example.Lezedata.net.ServerResponseObserver;
import com.example.Lezedata.ui.activity.baseClass.GBBaseVc;
import com.example.Lezedata.ui.activity.common.TransitionPage;
import com.example.Lezedata.ui.activity.goods.GoodsCell;
import com.example.Lezedata.ui.activity.goods.ProductDetail;
import com.example.Lezedata.ui.activity.login.LoginVc;
import com.example.Lezedata.ui.activity.person.PersonVc;
import com.example.Lezedata.ui.activity.record.PrizesRecord;
import com.example.Lezedata.util.GBInterface;
import com.example.Lezedata.ui.fragment.home.HomeBanner;
import com.example.Lezedata.ui.fragment.home.HomeWinners;
import com.example.Lezedata.util.GBUtil;

import java.util.ArrayList;
import java.util.List;

import bid.Bid;
import common.Common;
import in.srain.cube.views.GridViewWithHeaderAndFooter;

public class HomeVc extends GBBaseVc {

    @Override
    protected int getLayoutId() {
        return R.layout.activity_home_vc;
    }

    @Override
    protected boolean hideNavigationBack() {
        return false;
    }

    @Override
    public int navigationIcon() {
        return R.drawable.index_logo;
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.home_toolbar_menu, menu);
        setMenu();
        return true;
    }

    @Override
    public View.OnClickListener navigationOnClickListener() {
        return null;
    }

    GridViewWithHeaderAndFooter gridView;
    HomeWinners winners;
    HomeBanner banner;

    int pageStart = 0;
    int pageSize = 20;
    SwipeRefreshLayout swipeRefreshLayout;

    @Override
    protected void viewDidLoad() {
        super.viewDidLoad();
        gridViewConfig();
        addBannerView();

        addAction();
        resetData();
    }

    void gridViewConfig(){
        gridView = findViewById(R.id.collectionView);
        gridView.setNumColumns(2);
        gridView.setStretchMode(GridView.STRETCH_SPACING_UNIFORM);
        final int width = getWindowManager().getDefaultDisplay().getWidth();
        float dpw = (float)(GBUtil.pxTo2dp(this,width) - 30)/2;
        gridView.setColumnWidth(GBUtil.dpTo2px(this,dpw));
        gridView.setVerticalSpacing(GBUtil.dpTo2px(this,10));

        swipeRefreshLayout = (SwipeRefreshLayout)gridView.getParent();
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                resetData();
            }
        });
    }

    void addBannerView(){
        banner = new HomeBanner();
        banner.itemListener = new HomeBanner.OnTapItemListener() {
            @Override
            public void onTapItem(Bid.Banner data) {
                switch (data.getBannerType()){
                    case BT_BID:
                        goProductDetail(data.getContent());
                        break;
                    case BT_URL:
                        break;
                }
            }
        };
        banner.viewCreatedListener = new GBInterface() {
            @Override
            public void onViewCreated(View view) {
                gridView.addHeaderView(view);
                reloadData();
            }
        };
        getSupportFragmentManager().beginTransaction().add(banner,"HomeBanner").commit();
    }

    void addWinnerView(){
        winners = new HomeWinners();
        winners.onTapHomeWinnersListener = new HomeWinners.onTapHomeWinnersListener() {
            @Override
            public void onTapHomeWinnersItem(View view, Bid.WinPrizeListResponse.WinPrizeItem model) {
//                goProductDetail(model.getBidId());
            }
        };
        winners.viewCreatedListener = new GBInterface() {
            @Override
            public void onViewCreated(View view) {
                gridView.addHeaderView(view);
            }
        };
        getSupportFragmentManager().beginTransaction().add(winners,"HomeWinners").commit();
    }

    void addAction(){
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                GoodsCell cell = (GoodsCell)view;
                goProductDetail(cell.model.getBidId());
                Log.d("TAG", "onItemClick: ");
            }
        });
    }

    void loadBannerData(final ServerResponseObserver.requestCompleteListener listener){
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.BannerListResponse>() {
            @Override
            public void complete(Bid.BannerListResponse value, GBError t) {
                if (listener != null){
                    listener.complete();
                }
                if (t == null){
                    banner.reloadData(value);
                }
            }
        });
        GBNetRequest.stub().bannerList(Common.EmptyRequest.newBuilder().build(),observer);
    }

    void loadWinnerData(final ServerResponseObserver.requestCompleteListener listener){
        Common.PageInfo pageInfo = Common.PageInfo.newBuilder().setPageStart(0).setPageSize(4).build();
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.WinPrizeListResponse>() {
            @Override
            public void complete(Bid.WinPrizeListResponse value, GBError t) {
                if (listener != null){
                    listener.complete();
                }
                if (t == null){
                    if (value.getListCount() > 0){
                        addWinnerView();
                        winners.reloadData(value);
                    }else {
                        if (winners != null){
                            gridView.removeHeaderView(winners.contentView);
                            winners = null;
                        }
                    }

                }
            }
        });
        GBNetRequest.stub().winPrizeList(pageInfo,observer);
    }

    void loadBidData(final ServerResponseObserver.requestCompleteListener listener){
        Common.PageInfo pageInfo = Common.PageInfo.newBuilder().setPageStart(pageStart).setPageSize(pageSize).build();
        ServerResponseObserver observer = new ServerResponseObserver(new ServerResponseObserver.requestListener<Bid.BidListResponse>() {
            @Override
            public void complete(Bid.BidListResponse value, GBError t) {
                if (listener != null){
                    listener.complete();
                }
                if (t == null){
                    if (pageStart == 0){
                        models.clear();
                    }
                    if (value.getListCount() == pageSize){
                        pageStart++;
                    }
                    ArrayList<String> list = new ArrayList<>();
                    for (Bid.BidItem item:
                            value.getListList()) {
                        list.add(item.getGoodsId());
                    }
                    models.addAll(value.getListList());

                    BidDetailManager.getGoodsInfoForIds(list, new BidDetailManager.OnLoadListDataComplete() {
                        @Override
                        public void listInfoResponse(List<Bid.GoodsInfo> goodsInfoList) {
                            reloadData();
                        }
                    });
                }
            }
        });
        GBNetRequest.stub().bidList(pageInfo,observer);
    }

    ArrayList<Bid.BidItem> models = new  ArrayList<Bid.BidItem>();
    HomeVcAdapter adapter = new HomeVcAdapter(this,models);

    void reloadData(){
        gridView.setAdapter(adapter);
    }

    /// 重置数据
    void resetData(){
        pageStart = 0;
        loadBannerData(new ServerResponseObserver.requestCompleteListener() {
            @Override
            public void complete() {
                loadWinnerData(new ServerResponseObserver.requestCompleteListener() {
                    @Override
                    public void complete() {
                        loadBidData(new ServerResponseObserver.requestCompleteListener() {
                            @Override
                            public void complete() {
                                swipeRefreshLayout.setRefreshing(false);
                            }
                        });
                    }
                });
            }
        });
    }

    void loadMoreData(){
        loadBidData(null);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    void setMenu(){
        setOnMenuItemClickListener(new androidx.appcompat.widget.Toolbar.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                switch (item.getItemId()){
                    case R.id.notice:
                        goNewMessage();
                        break;
                    case R.id.person:
                        tapPerson();
                        break;
                }
                return false;
            }
        });
    }

    final void tapPerson(){
        if (LoginManager.instance().isLogin()){
            goPerson();
        }else {
            goLogin();
        }
    }

    // 登录
    final void goLogin(){
        jumpActivity(LoginVc.class);
    }

    // 个人
    final void goPerson(){
        jumpActivity(PersonVc.class);
    }

    /*新消息*/
    final void goNewMessage(){
        jumpActivity(NewMessageVc.class);
    }

    // 产品详情
    final void goProductDetail(String goodsId){
        Intent intent = new Intent(mContext,ProductDetail.class);
        intent.putExtra("bid",goodsId);
        jumpActivityIntent(intent);
    }

    public static class HomeVcAdapter extends BaseAdapter {

        Context context;
        ArrayList<Bid.BidItem> models;

        public HomeVcAdapter(Context context,ArrayList<Bid.BidItem> models){
            this.context = context;
            this.models = models;
        }

        @Override
        public int getCount() {
            return models.size();
        }

        @Override
        public Bid.BidItem getItem(int position) {
            return models.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null){
                convertView = new GoodsCell(context,null);
            }
            Bid.BidItem model = getItem(position);
            GoodsCell goodsCell = (GoodsCell) convertView;
            goodsCell.setModel(model);
            return convertView;
        }
    }
}